package com.gitee.srurl.system.biz;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gitee.srurl.core.domain.SucBlacklistDomain;
import com.gitee.srurl.core.domain.SusVisitorRecordDomain;
import com.gitee.srurl.core.factory.ShortUrlFactory;
import com.gitee.srurl.core.mapper.SucBlacklistMapper;
import com.gitee.srurl.core.mapper.SusVisitorRecordMapper;
import com.gitee.srurl.system.vo.DashboardRecentDataVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

/**
 * @author zxw
 * @date 2023/5/11 20:50
 */
@Component
@RequiredArgsConstructor
public class DashboardBiz {

    private final SusVisitorRecordMapper visitorRecordMapper;

    private final SucBlacklistMapper blacklistMapper;

    public DashboardRecentDataVO recentData(Date startDate, Date endDate) {

        if (startDate == null || endDate == null) {
            DateTime now = DateTime.now();
            startDate = DateUtil.beginOfDay(now);
            endDate = DateUtil.endOfDay(now);
        } else {
            if (startDate.after(endDate)) {
                Date temp = startDate;
                startDate = endDate;
                endDate = temp;
            }

            startDate = DateUtil.beginOfDay(startDate);
            endDate = DateUtil.endOfDay(endDate);
        }

        // 查询短链接生成数量
        long generateNum = ShortUrlFactory.getShortUrlConfig().getDataStore().getGenerateNum(startDate, endDate);
        // 查询访问次数
        LambdaQueryWrapper<SusVisitorRecordDomain> visitorRecordQueryWrapper = new LambdaQueryWrapper<>();
        visitorRecordQueryWrapper.between(SusVisitorRecordDomain::getVisitTime, startDate, endDate);
        long visitNum = Optional.ofNullable(visitorRecordMapper.selectCount(visitorRecordQueryWrapper)).orElse(0L);
        // 查询访问IP量
        long visitIpNum = Optional.ofNullable(visitorRecordMapper.countDistinctIp(startDate, endDate)).orElse(0L);
        // 查询黑名单数量
        LambdaQueryWrapper<SucBlacklistDomain> blacklistWrapper = new LambdaQueryWrapper<>();
        blacklistWrapper.between(SucBlacklistDomain::getCreateTime, startDate, endDate);
        long blacklistNum = Optional.ofNullable(blacklistMapper.selectCount(blacklistWrapper)).orElse(0L);

        return DashboardRecentDataVO.builder()
                .shortUrlGenerateNum(generateNum)
                .visitNum(visitNum)
                .visitIpNum(visitIpNum)
                .blacklistNum(blacklistNum)
                .build();
    }
}
